//
//  RxFileUploadDownloadViewController.swift
//  DemoProject
//
//  Created by Hao on 2018/8/28.
//  Copyright © 2018年 hao. All rights reserved.
//

import UIKit

class RxFileUploadDownloadViewController: BaseViewController {

    let disposeBag = DisposeBag()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        progressView.snp.makeConstraints({ (make) in
            make.center.equalTo(self.view)
            make.width.equalTo(200)
            make.height.equalTo(10)
        })
//        _rxTestUploadFile()
        _testDownloadBindProgress()
    }
    
    let progressView = UIProgressView(progressViewStyle: .default)
    
    private func _rxTestUploadFile() {
        //需要上传的文件路径
        let fileURL = Bundle.main.url(forResource: "hangge", withExtension: "zip")
        //服务器路径
        let uploadURL = URL(string: "http://www.hangge.com/upload.php")!
        
        //将文件上传到服务器
        RxAlamofire.upload(fileURL!, urlRequest: try! urlRequest(.post, uploadURL))
            .subscribe(onNext: { element in
                print(info: "--- 开始上传 ---")
                element.uploadProgress(closure: { (progress) in
                    print(info: "当前进度：\(progress.fractionCompleted)")
                    print(info: "  已上传载：\(progress.completedUnitCount/1024)KB")
                    print(info: "  总大小：\(progress.totalUnitCount/1024)KB")
                })
            }, onError: { error in
                print(info: "上传失败! 失败原因：\(error)")
            }, onCompleted: {
                print(info: "上传完毕!")
            })
            .disposed(by: disposeBag)
    }

    /// 上传文件并绑定进度
    private func _rxTestUploadFileBindProgress() {
        //需要上传的文件路径
        let fileURL = Bundle.main.url(forResource: "hangge", withExtension: "zip")
        //服务器路径
        let uploadURL = URL(string: "http://www.hangge.com/upload.php")!
        
        //将文件上传到服务器
        RxAlamofire.upload(fileURL!, urlRequest: try! urlRequest(.post, uploadURL))
            .map{ request in
                //返回一个关于进度的可观察序列
                Observable<Float>.create { observer in
                    request.uploadProgress(closure: { (progress) in
                        observer.onNext(Float(progress.fractionCompleted))
                        if progress.isFinished{
                            observer.onCompleted()
                        }
                    })
                    return Disposables.create()
                }
            }
            .flatMap { $0 }
            .bind(to: progressView.rx.progress) //将进度绑定UIProgressView上
            .disposed(by: disposeBag)
    }
    
    /// 上传 MultipartFormData 类型的文件数据（类似于网页上 Form 表单里的文件提交）
    private func _testUploadFormData() {
        //字符串
        let strData = "hangge.com".data(using: String.Encoding.utf8)
        //数字
        let intData = String(10).data(using: String.Encoding.utf8)
        //文件1
        let path = Bundle.main.url(forResource: "0", withExtension: "png")!
        let file1Data = try! Data(contentsOf: path)
        //文件2
        let file2URL = Bundle.main.url(forResource: "1", withExtension: "png")
        
        //服务器路径
        let uploadURL = URL(string: "http://www.hangge.com/upload2.php")!
        
        //将文件上传到服务器
        Alamofire.upload(
            multipartFormData: { multipartFormData in
                multipartFormData.append(strData!, withName: "value1")
                multipartFormData.append(intData!, withName: "value2")
                multipartFormData.append(file1Data, withName: "file1",
                                         fileName: "php.png", mimeType: "image/png")
                multipartFormData.append(file2URL!, withName: "file2")
        },
            to: uploadURL,
            encodingCompletion: { encodingResult in
                switch encodingResult {
                case .success(let upload, _, _):
                    upload.responseJSON { response in
                        print(info: response)
                    }
                case .failure(let encodingError):
                    print(info: encodingError)
                }
        })
    }
    
}

// MARK: 下载
extension RxFileUploadDownloadViewController {
    
    fileprivate func _testDownload() {
        //指定下载路径（文件名不变）
        let destination: DownloadRequest.DownloadFileDestination = { _, response in
            let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
            // 更改下载后存储的文件名
            // let fileURL = documentsURL.appendingPathComponent("file1/myLogo.png")
            let fileURL = documentsURL.appendingPathComponent(response.suggestedFilename!)
            //两个参数表示如果有同名文件则会覆盖，如果路径中文件夹不存在则会自动创建
            return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
        }
        
        //需要下载的文件
        let fileURL = URL(string: "http://www.hangge.com/blog/images/logo.png")!
        
        //开始下载
        RxAlamofire.download(URLRequest(url: fileURL), to: destination)
            .subscribe(onNext: { element in
                print(info: "开始下载。")
            }, onError: { error in
                print(info: "下载失败! 失败原因：\(error)")
            }, onCompleted: {
                print(info: "下载完毕!")
            })
            .disposed(by: disposeBag)
    }
    
    fileprivate func _testDownloadBindProgress() {
        //指定下载路径（文件名不变）
        let destination: DownloadRequest.DownloadFileDestination = { _, response in
            let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
            // 更改下载后存储的文件名
            // let fileURL = documentsURL.appendingPathComponent("file1/myLogo.png")
            let fileURL = documentsURL.appendingPathComponent(response.suggestedFilename!)
            //两个参数表示如果有同名文件则会覆盖，如果路径中文件夹不存在则会自动创建
            return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
        }
        let fileURL = URL(string: "http://www.hangge.com/blog/images/logo.png")!
        //开始下载
        RxAlamofire.download(URLRequest(url: fileURL), to: destination)
            .map{request in
                //返回一个关于进度的可观察序列
                Observable<Float>.create{observer in
                    request.downloadProgress(closure: { (progress) in
                        observer.onNext(Float(progress.fractionCompleted))
                        if progress.isFinished{
                            observer.onCompleted()
                        }
                    })
                    return Disposables.create()
                }
            }
            .flatMap{ $0 }
            .bind(to: progressView.rx.progress) //将进度绑定UIProgressView上
            .disposed(by: disposeBag)
    }
    
}



